from genericpath import isdir, isfile
from flask import Flask, abort
import os


app = Flask(__name__, static_folder='../front/build', static_url_path='/')


root_dir = '/remote/iosg/strat-1/buckets/analysis.derived.coin/live/plot/kline_plot'


@app.errorhandler(404)
def resource_not_found(e):
    return e, 404


@app.route('/root_dir')
def api_root_dir():
  return root_dir


@app.route('/')
def api_index():
  return app.send_static_file('index.html')


# not used file_path, as react route can get path value
@app.route('/plot/<path:file_path>')
def api_plot(file_path):
  return app.send_static_file('index.html')


@app.route('/data/')
@app.route('/data/<path:path>')
def api_data(path=""):
  file_path = os.path.join(root_dir, path)
  if not os.path.exists(file_path):
    abort(404, description=path + "is invalid.")
  elif os.path.isfile(file_path):
    with open(file_path, 'r') as f:
      data = f.read()
      return data
  elif os.path.isdir(file_path):
    files = os.listdir(file_path)
    if len(files) == 0:
      abort(404, description=path + "is empty.")
    return "\n".join(files)


if __name__ == '__main__':
  app.run()